package server.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

import proprietes.Protocol;

import server.dao.MySqlDao;

public class CoreServer implements Runnable {
	private ServerSocket serverSocket;
	private Socket clientSocket;

	BufferedReader is = null;
	PrintStream os = null;

	public CoreServer() {
		try {
			serverSocket = new ServerSocket(Integer.parseInt(Protocol.PORT
					.getValue()));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	@Override
	public void run() {
		while (true) {
			try {
				clientSocket = serverSocket.accept();
				is = new BufferedReader(new InputStreamReader(
						clientSocket.getInputStream()));
				os = new PrintStream(clientSocket.getOutputStream());

				String methodName = is.readLine();

				try {
					Method method = this.getClass().getMethod(methodName, null);
					method.setAccessible(true);
					try {
						method.invoke(this);
					} catch (IllegalArgumentException e) {
						System.out.println("IllegalArgumentException");
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						System.out.println("IllegalAccessException");
						// e.printStackTrace();
					} catch (InvocationTargetException e) {
						System.out.println("InvocationTargetException");
						e.printStackTrace();
					}
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				System.out.println(e);
			}
		}

	}

	public void logUser() {
		String userName;
		String passwd;
		try {
			userName = is.readLine();
			passwd = is.readLine();
			String ip = clientSocket.getInetAddress().toString();
			MySqlDao mDao = new MySqlDao();
			if (mDao.login(userName, passwd,ip)) {
				os.println("successful");
			} else {
				os.println("error");
			}
			os.flush();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	private String getIpAdresClient(InetAddress inetAddress) {
		StringTokenizer stringIp = new StringTokenizer(inetAddress.getAddress().toString(),":",true);
		return stringIp.nextToken();
	}
}